"""
1. 批量注册用户 register
2. 批量登录用户   login
3. 请求使用设备请求 use_set
4. 获取数据库已注册的用户信息 _account
5. 批量注销用户 del_account
"""
import json
import os.path
from json import JSONDecodeError

import requests

from common.logger import logFile
from common.utils import enconde_bs64, decode64_str
from utils import ContMysql
requests.packages.urllib3.disable_warnings()
logger = logFile('mqtt', 'all')
s = requests.Session()
# 配置请求头
HEADERS = {"Content-Type": "application/json"}
# https://192.168.10.146:8081
# https://47.102.214.108
# https://192.168.10.233:8081
script_env = "https://www.retone-hearing.fit"
# script_env = 'https://47.102.214.108'


def send_post(url, data, cookie=None):
    if cookie is None:
        res = requests.post(url, data=enconde_bs64(data), verify=False, headers=HEADERS)
        return res
    else:
        cookies = {"hearingaid_user": cookie}
        res = requests.post(url, data=enconde_bs64(data), verify=False, headers=HEADERS, cookies=cookies)
        return res


def register(num):
    """
    获取验证验证码接口
    :param num: 注册用户数
    :return: 返回验证码列表
    """
    global FAIL_NUM
    GET_MESSAGE = script_env + '/microServiceUser/responseEncode/requestDecode/getVerificationCode'
    notice_data = {
        "authenticationMethod": "EMAIL",
        "email": f"verify{num}@qq.com",
        "verificationCodeType": 2
    }
    # logger.error(notice_data)
    res = send_post(GET_MESSAGE, notice_data)
    # logger.error(res.json()['data'])
    # 检查错误
    if res.status_code != 200 or res.json()['data'] is None:
        logger.error('=============调用短信息接口失败, 请检查================')
        logger.error(res.status_code, res.text)
    dic = json.loads(decode64_str(res.json()['data']))
    # 调用注册接口
    set_user_info(f'tester{num}', dic['validateCode'], dic['token'])


def set_user_info(account, notice, cookie, sourcePlatform='RETONE_FIT'):
    """
    用户注册注册接口
    :param account: 设置用户名
    :param password: 设置用户密码
    :param notice: 短信息,列表需要先提取
    :param sourcePlatform: 平台
    :return:
    """
    URL_REGISTER = script_env + '/microServiceUser/responseEncode/requestDecode/register'
    info = {
        "account": account,
        "password": 'cc1234',
        "notice": notice,
        "sourcePlatform": sourcePlatform
    }
    res = send_post(URL_REGISTER, info, cookie)

    # logger.error(res.json())

    if res.status_code != 200 or res.json()['data'] is None:
        logger.error('================注册接口调用错误===============')
        logger.error(res.json())


def login(username, password='cc1234'):
    """
    登录接口
    :param username: 用户名
    :param password: 密码
    :return: 返回用户cookie
    """
    user = username
    passwd = password
    # 登录
    login_url = script_env + '/microServiceUser/responseEncode/requestDecode/login'

    info = {
        "type": 0,
        "sourcePlatform": "RETONE_FIT",
        "password": passwd,
        "loginObject": user
    }
    res = send_post(login_url, info)
    if res.status_code > 400 or (res.json()['data'] == None and res.json()['description'] != None):
        logger.error(
            "=============  登录   接口调用失败==========" + '\n' + str(res.json()) + f'res.status_code = {res.status_code}')
        return False
    return str(res.cookies.values()[0])


def del_account(user, pswd):
    """
    注销用户
    :return:
    """
    del_url = script_env + '/microServiceUser/needAppUserAuth/responseEncode/requestDecode/getCurrentUserDeleteCode'
    info = {
        "authenticationMethod": "EMAIL"
    }
    cookie = login(user, pswd)
    # logger.error(f"登录返回的验证码:{cookie}")
    res = send_post(del_url, info, cookie)
    if res.status_code != 200 or res.json()['data'] is None:
        logger.error("=============删除接口获取验证码出现错误 ==============")
        logger.error(res.json())
    result = decode64_str(res.json()['data'])
    vilidataCode = json.loads(result)['validateCode']
    # logger.error(f"获取验证码: res = {vilidataCode}")
    # 使用验证码注销用户
    upset_user = 'https://192.168.10.146:8081/microServiceUser/needAppUserAuth/responseEncode/requestDecode/deleteCurrentUser'
    _info = {"notice": vilidataCode}
    res = send_post(upset_user, _info, cookie)
    if res.status_code != 200 or res.json()['description'] is not None:
        logger.error("=============   注销用户   获取验证码出现错误 ==============")
    else:
        logger.error("注销成功")


def _account():
    """
    # 获取注册账号信息
    :return:
    """
    mydb = ContMysql()
    data = mydb.select_db('select account from app_user a1,app_user_usable_platform_info a2 '
                          'where a1.id=a2.id and a2.retone_fit_platform_state=1')
    if os.path.exists('account/user.txt'):
        os.remove('account/user.txt')
    if os.path.exists('account/tester.txt'):
        os.remove('account/tester.txt')
    for username in data:
        if username[0].startswith('user'):
            with open('account/user.txt', mode='a', encoding='utf-8') as f:
                f.write(username[0])
                f.write('\n')
        if username[0].startswith('tester'):
            with open('account/tester.txt', mode='a', encoding='utf-8') as f:
                f.write(username[0])
                f.write('\n')


def mqtt_conf(cookie):
    """
    去登录接口获取cookie信息,调用该接口
    :param username: 用户名
    :param passwd: 密码
    :return: 返回mqtt配置信息
    """
    mqtt_url = script_env + '/platformRetoneFit/api/mqtt/needAppUserAuth/responseEncode/requestDecode/getMqttConnectProperties'
    info = {}
    # cookie = login(username, passwd)
    res = send_post(mqtt_url, info, cookie)
    if res.status_code != 200 or res.json()['data'] is None:
        logger.error('===== 获取mqtt配置信息接口失败 =========')
        logger.error(res.json())
    data_str = decode64_str(res.json()['data'])
    data = json.loads(data_str)
    dic_conf = {
        "appGuestPassword": "123456@appGuest.retone",
        "port": data['port'],
        "appGuestSendTopic": data['appGuestSendTopic'],
        "appGuestReceiveTopic": data['appGuestReceiveTopic'],
        "appGuestReceiveClientId": data['appGuestReceiveClientId'],
        "url": data['url'],
        "appGuestName": "appGuest"
    }
    # logger.error(dic_conf)
    return dic_conf


def get_personal_info(cookie):
    """
    获取各人信息
    :param username: 用户名
    :param passwd: 密码
    :return: 返回mqtt配置信息
    """
    mqtt_url = script_env + '/platformRetoneFit/api/needAppUserAuth/responseEncode/requestDecode/getCurrentPersonalInfo'
    info = {}
    # cookie = login(username, passwd)
    res = send_post(mqtt_url, info, cookie)
    if res.status_code != 200 or res.json()['data'] is None:
        logger.error('=====  获取个人  信息接口失败 =========')
        logger.error(res.json(), res.status_code)
    data_str = decode64_str(res.json()['data'])
    data = json.loads(data_str)

    # logger.error(dic_conf)
    return data


def bind_set(cookie, devicenum):
    """
    绑定设备 设备型号可以随机生成
    :return: 返回绑定设备
    """
    bind_set_url = script_env + '/platformRetoneFit/api/deviceBinding/needAppUserAuth/responseEncode/requestDecode/binding'
    info = {
        "deviceNumber": devicenum,
        "deviceTypeCode": "1",
        "chipTypeCode": "1"
    }
    res = send_post(bind_set_url, info, cookie)
    if res.status_code != 200 or res.json()['description'] is not None:
        logger.error(f"=======  绑定设备错误  返回:status_code={res.status_code},resp={res.text}==========")
    return info['deviceNumber']


def use_set(cookie, devicenum):
    """
    使用设备的信息, 使用设备的用户
    :param cookie: 用户
    :return:
    """
    user_set_url = script_env + '/platformRetoneFit/api/deviceBinding/needAppUserAuth/responseEncode/requestDecode/deviceUse'
    info = {
        "leftDevice": {
            "deviceNumber": devicenum,
            "firmwareVersion": "1.0.38"
        },
        "rightDevice": {
            "deviceNumber": devicenum+'1',
            "firmwareVersion": "1.0.38"
        }
    }
    res = send_post(user_set_url, info, cookie)
    # data = decode64_str(res.json()['data'])
    # data = json.loads(data)
    if res.status_code > 400 or (res.json()['data'] == None and res.json()['description'] != None):
        logger.error(f"=======使用设备 错误 返回:status_code={res.status_code},resp={res.text}==========")



def check_device(cookie):
    check_devices_url = script_env + '/platformRetoneFit/api/deviceBinding/needAppUserAuth/responseEncode/requestDecode/getDeviceBindingList'
    info = {}
    res = send_post(check_devices_url, info, cookie)
    if res.status_code > 400 or (res.json()['data'] == None and res.json()['description'] != None):
        logger.error(f"=======检查设备接口错误 返回:status_code={res.status_code},resp={res.text}==========")
        return ('==========查询绑定设备信息出现错误  =====')
    data = decode64_str(res.json()['data'])
    data = json.loads(data)
    logger.info(data)


def add_memo_(cookie):
    # 添加 删除的过程
    url = '/platformRetoneFit/api/memo/needAppUserAuth/responseEncode/requestDecode/addMemo'
    data = {
        "note": '2000个并发测试',
        "activeTime": "2023-04-21 03:00:00",
        "memoTypeEnum": "EVERY_DAY",
    }
    resp = send_post(script_env+url, data, cookie)
    if resp.status_code > 400 or (resp.json()['data'] == None and resp.json()['description'] != None):
        # 请求出错
        if resp.json()['description'] == "用户备忘提醒数量超过最大值":
            logger.error('用户备忘提醒数量超过最大值')
        else:
            logger.error(f"=======错误返回:status_code={resp.status_code},resp={resp.text}==========")
    else:
        # add_memo_resp = json.loads(decode64_str(resp.json()['data']))
        # print(add_memo_resp)
        # delete_memo = '/platformRetoneFit/api/memo/needAppUserAuth/responseEncode/requestDecode/batchDeleteMemo'
        # del_memo_data = {"memoIdList": [add_memo_resp['memoId']]}
        # send_post(script_env+delete_memo, del_memo_data, cookie)
        # if resp.status_code > 400 or (resp.json()['data'] == None and resp.json()['description'] != None):
        #     logger.error(resp.json())
        # else:
        #     logger.info("del memo success")
        pass

def del_memo(username):
    cookie = login(username)
    get_id_url = '/platformRetoneFit/api/memo/needAppUserAuth/responseEncode/requestDecode/getAllMemo'
    resp = send_post(script_env+get_id_url, data='', cookie=cookie)
    try:
        if resp.status_code > 400 or (resp.json()['data'] is None and resp.json()['description'] is not None):
            logger.info(f"=======错误返回:status_code={resp.status_code},resp={resp.text}==========")
        else:
            if resp.json()['data']:
                data_list = json.loads(decode64_str(resp.json()['data']))
                print(data_list)
                id_list = []
                for _ in data_list:
                    temp = _['memoId']
                    id_list.append(temp)
                delete_memo = '/platformRetoneFit/api/memo/needAppUserAuth/responseEncode/requestDecode/batchDeleteMemo'
                data = {
                    "memoIdList": id_list
                }
                resp1 = send_post(script_env+delete_memo, data, cookie)
                if resp1.status_code > 400 or (
                        resp1.json()['data'] is None and resp1.json()['description'] is not None):
                    logger.info(f"=======错误返回:status_code1={resp1.status_code},resp1={resp1.text}==========")
                else:
                    logger.info('success')
    except TypeError:
        logger.info(TypeError)
    except JSONDecodeError:
        logger.info("Response could not be decoded as JSON")
    except KeyError:
        logger.info("Response did not contain expected key 'data'")



if __name__ == '__main__':
    # _account()
    # 注册一个verify1@qq.com的账号,在平台上注册WECHAT_HA
    # del_memo('cc1234')
    cookie = login('cc1234')
    add_memo(cookie)

